package org.ohos.sample.jsplugin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import ohos.agp.components.webengine.JsCallback;
import ohos.agp.components.webengine.WebView;
import org.ffsky.jsplugin.JsPlugin;
import org.ohos.sample.webview.home.WebAbility;

public class PageJsPlugin extends JsPlugin {

    @Override
    public void bindJsBridge(WebView webView) {
        super.bindJsBridge(webView);
        webView.addJsCallback("page_openPage", new JsCallback() {
            @Override
            public String onCallback(String jsonArgs) {
                JSONObject json = JSON.parseObject(jsonArgs);
                if (json.containsKey("url")) {
                    String url = json.getString("url");
                    WebAbility.start(getAbility(), url);
                    return JsPlugin.RESULT_OK;
                }
                return JsPlugin.RESULT_ERROR;
            }
        });
        webView.addJsCallback("page_closePage", new JsCallback() {
            @Override
            public String onCallback(String s) {
                if(getAbility()!=null){
                    getAbility().terminateAbility();
                }
                return JsPlugin.RESULT_OK;
            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
